package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.expection.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Ren(任佳宝)
 * @Description: CourseBaseInfoServiceImpl
 * @Date: 2024/8/15 下午5:03
 * @Version: 1.0
 */
@Slf4j
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Resource
    private CourseMarketMapper courseMarketMapper;

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Resource
    private TeachplanMapper teachplanMapper;

    @Resource
    private CourseTeacherMapper courseTeacherMapper;

    /**
     * 安城分页查询
     *
     * @param pageParams           分页参数
     * @param queryCourseParamsDto 查询条件
     * @return 查询结果
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        // 拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 根据名称模糊查询, 在sql中拼接 course_base.name like %值%
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        // 根据课程的审核状态 course_base.audit_status = ?
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        // 根据课程发布状态拼接条件
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());

        // 创建page分页参数对象, 参数： 当前页码,每页记录数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 开始进行分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        // 数据列表
        List<CourseBase> items = pageResult.getRecords();
        // 总记录数
        long total = pageResult.getTotal();
        // 创建返回前端的Vo对象
        PageResult<CourseBase> pageVo = new PageResult<>(items, total, pageParams.getPageNo(), pageParams.getPageSize());

        // 返回数据
        return pageVo;
    }

    /**
     * 添加课程
     *
     * @param CompanyId 机构Id
     * @param dto       课程信息
     * @return 返回刚刚添加的课程信息
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long CompanyId, AddCourseDto dto) {

        // 参数的合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            // throw new RuntimeException("课程名称为空");
            XueChengPlusException.cast("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            // throw new RuntimeException("课程分类为空");
            XueChengPlusException.cast("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            // throw new RuntimeException("课程分类为空");
            XueChengPlusException.cast("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            // throw new RuntimeException("课程等级为空");
            XueChengPlusException.cast("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            // throw new RuntimeException("教育模式为空");
            XueChengPlusException.cast("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            // throw new RuntimeException("适应人群为空");
            XueChengPlusException.cast("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            // throw new RuntimeException("收费规则为空");
            XueChengPlusException.cast("收费规则为空");
        }

        // 向课程基本信息表写入数据
        CourseBase courseBaseNew = new CourseBase();
        BeanUtils.copyProperties(dto, courseBaseNew); // 属性名称一致就可以拷贝
        courseBaseNew.setCompanyId(CompanyId);
        // 设置默认字段
        courseBaseNew.setCreateDate(LocalDateTime.now());
        // 审核状态默认为 未提交
        courseBaseNew.setAuditStatus("202002");
        // 发布状态默认为 未发布
        courseBaseNew.setStatus("203001");

        int insert = courseBaseMapper.insert(courseBaseNew);
        if (insert <= 0) {
            // 提示信息,事务要回滚 所以抛异常
            // throw new RuntimeException("添加课程失败");
            XueChengPlusException.cast("添加课程失败");
        }
        // 向课程营销表写入数据
        CourseMarket courseMarketNew = new CourseMarket();
        // 将页面输入的数据拷贝到courseMarket
        BeanUtils.copyProperties(dto, courseMarketNew);
        // 设置主键为课程的id
        courseMarketNew.setId(courseBaseNew.getId());
        // 保存营销信息
        saveCourseMarket(courseMarketNew);
        // 从数据库查询课程的详细信息，包括两部分
        return getCourseBaseInfo(courseBaseNew.getId());
    }

    /**
     * @param courseId 课程Id
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        // 从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        // 从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        // 组装在一起
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        // 通过courseCategoryMapper查询分类信息，将分类名称放在courseBaseInfoDto对象
        // 查询课程大分类名称
        LambdaQueryWrapper<CourseCategory> mtNameWrapper = new LambdaQueryWrapper<>();
        mtNameWrapper.eq(true, CourseCategory::getId, courseBase.getMt());
        CourseCategory mtName = courseCategoryMapper.selectOne(mtNameWrapper);
        // 查询课程小分类名称
        LambdaQueryWrapper<CourseCategory> stNameWrapper = new LambdaQueryWrapper<>();
        stNameWrapper.eq(true, CourseCategory::getId, courseBase.getSt());
        CourseCategory stName = courseCategoryMapper.selectOne(stNameWrapper);

        courseBaseInfoDto.setMtName(mtName.getName());
        courseBaseInfoDto.setStName(stName.getName());
        return courseBaseInfoDto;
    }

    /**
     * @param editCourseDto 要要改的课程信息
     * @return 修改之后课程信息
     */
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {

        // 拿到课程id
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        // 去数据库查看是否存在
        if (courseBase == null) {
            XueChengPlusException.cast("课程已不存在");
        }
        // 查看课程是否属于该机构
        if (!companyId.equals(courseBase.getCompanyId())) {
            // 不属于 抛出异常
            XueChengPlusException.cast("当前课程不属于你的机构无法修改");
        }

        // 封装数据
        BeanUtils.copyProperties(editCourseDto, courseBase);
        // 修改时间
        courseBase.setChangeDate(LocalDateTime.now());
        // 更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if (i <= 0) {
            XueChengPlusException.cast("修改课程失败");
        }
        // 更新营销信息
        // 数据库中的营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        courseMarketMapper.updateById(courseMarket);

        return getCourseBaseInfo(courseBase.getId());
    }

    // 单独写一个方法保存营销方法,逻辑: 存在就更新,不存再就添加
    private void saveCourseMarket(CourseMarket courseMarketNew) {

        // 参数的合法性校验
        String charge = courseMarketNew.getCharge();
        if (StringUtils.isEmpty(charge)) {
            // throw new RuntimeException("收费规则为空");
            XueChengPlusException.cast("收费规则为空");
        }
        // 如果课程收费,但是价格没有填写也需要抛出异常
        if ("201001".equals(charge)) {
            Float price = courseMarketNew.getPrice();
            if (price == null || price < 0) {
                // throw new RuntimeException("收费价格为空并且课程价格必须大于0");
                XueChengPlusException.cast("收费价格为空并且课程价格必须大于0");
            }
        }
        // 从数据库查询营销信息 逻辑：存在->修改,不存再->添加
        CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());
        if (courseMarket == null) {
            // 没有就插入
            courseMarketMapper.insert(courseMarketNew);
        } else {
            // 有就修改
            courseMarketMapper.updateById(courseMarketNew);
        }
    }

    @Transactional
    @Override
    public void delectCourse(Long companyId, Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId()))
            XueChengPlusException.cast("只允许删除本机构的课程");
        // 删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.eq(CourseTeacher::getCourseId, courseId);
        courseTeacherMapper.delete(teacherLambdaQueryWrapper);
        // 删除课程计划 teachplanMapper courseTeacherMapper
        LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanLambdaQueryWrapper.eq(Teachplan::getCourseId, courseId);
        teachplanMapper.delete(teachplanLambdaQueryWrapper);
        // 删除营销信息
        courseMarketMapper.deleteById(courseId);
        // 删除课程基本信息
        courseBaseMapper.deleteById(courseId);
    }
}
